package com.macrosolution.exdebito

import grails.converters.JSON;
import grails.plugin.springsecurity.annotation.Secured;
import grails.transaction.Transactional;

import java.text.SimpleDateFormat
import java.util.Date;
import static org.springframework.http.HttpStatus.*


@Secured(['ROLE_ADMIN','ROLE_AMM','ROLE_BCKOFF'])
class PeritoController {
	def springSecurityService
    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

	def index(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        respond Perito.list(params), model:[peritoInstanceCount: Perito.count()]
    }

	def list={
		Set<Perito> periti = Perito.findAll();		
       		render view:'list', model:[periti: periti]
    }

    def show(){
		boolean lp = false
		if(params.lp){
			lp = params.getBoolean('lp')
		}
		render view:'/perito/show', model:[peritoInstance:Perito.get(params.getLong('id')),lp:lp]
    }

	@Secured(['ROLE_ADMIN','ROLE_AMM'])
    def create() {
        respond new Perito(params)
    }

	@Secured(['ROLE_ADMIN','ROLE_AMM'])
	@Transactional
	def save(){
		Perito perito
		if(Perito.get(params.getLong('id'))){
			perito=Perito.get(params.getLong('id'))
			perito.setProperties(params)
			if(perito?.fiscalAddress){
				perito.fiscalAddress.save(flush:true)
			}
		}else{
			perito = Perito.newInstance(params)			
			if(params.getLong('fiscal_province')){
			Address fiscalAddress = perito.fiscalAddress?:new Address()
			fiscalAddress.province=Provincia.get(params.getLong('fiscal_province'))
			if(params.getLong('fiscal_municipality')){
				fiscalAddress.municipality=Comune.get(params.getLong('fiscal_municipality'))
				fiscalAddress.cap=params.fiscal_cap
			}
			if(params.fiscal_address){
				fiscalAddress.address=params.fiscal_address
			}
			fiscalAddress.save(flush:true)
			perito.fiscalAddress = fiscalAddress
			perito.save(flush:true)
			}
		}
	
		perito.save(flush: true)
		redirect uri:'/perito/list'
	}

	@Secured(['ROLE_ADMIN','ROLE_AMM'])
	@Transactional
	def update(){
		def perito=Perito.get(params.getLong('peritoId'))
		perito.setProperties(params)
			if(params.getLong('fiscal_province')){
				Address fiscalAddress = perito.fiscalAddress?:new Address()
				fiscalAddress.province=Provincia.get(params.getLong('fiscal_province'))
				if(params.getLong('residence_municipality')){
					fiscalAddress.municipality=Comune.get(params.getLong('fiscal_municipality'))
					fiscalAddress.cap=params.fiscal_cap
				}
				if(params.fiscal_address){
					fiscalAddress.address=params.fiscal_address
				}
				fiscalAddress.save(flush:true)
				perito.fiscalAddress = fiscalAddress
			}
		perito.save(flush:true)
		redirect uri:'/perito/list'
	}

	@Secured(['ROLE_ADMIN','ROLE_AMM'])
    def edit(){
		render view:'/perito/edit', model:[peritoInstance:Perito.get(params.getLong('id'))]
    }

	@Secured(['ROLE_ADMIN','ROLE_AMM'])
	@Transactional
	def delete(){
		Perito perito = Perito.get(params.id)
		println perito.name
		String message
		if(perito){
			List<AnomaliaBancaria> anomalie = AnomaliaBancaria.findAllByPerito(perito)
			for(int i=0 ; i < anomalie.size() ; i++){
				anomalie[i].perito = null
				anomalie[i].save(flush:true)
			}
			User secUser =springSecurityService.currentUser
				List<String> auths =secUser.authorities*.authority
				if(auths.contains("ROLE_ADMIN") ||auths.contains("ROLE_AMM")){
					perito.delete(flush:true)
				}
					message="{'message':'Perito cancellato con successo!'}"
		}else{
			message="{'message':'impossibile trovare il perito selezionato'}"
		}
		render JSON.parse(message) as JSON
	}


    protected void notFound() {
        request.withFormat {
            form {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'peritoInstance.label', default: 'Perito'), params.id])
                redirect action: "index", method: "GET"
            }
            '*'{ render status: NOT_FOUND }
        }
    }
}
